package cn.xhz.gdal.util;

import org.gdal.ogr.*;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 这里封装gdal可能使用到的一些方法
 *
 * @author life-oss
 * @since 2022/12/15
 */
public class GDALUtils {
    /**
     * 判断是否有该图层
     * @param dataSource 数据源
     * @param layerName 图层名称
     * @return true有 反之无
     */
    public static boolean isHaveLayer(DataSource dataSource,String layerName){
        for (int i = 0; i < dataSource.GetLayerCount(); i++) {
            Layer layer = dataSource.GetLayer(0);
            if (layer.GetName().equals(layerName)){
                return true;
            }
        }
        return false;
    }

    /**
     * 根据图层获取当前的属性
     * @param layer 图层对象
     * @return 前者为字段名 后者为字段类型
     */
    public static Map<String, String> listField(Layer layer) {
        if (Objects.isNull(layer)) {
            throw new RuntimeException("没有图层对象");
        }
        FeatureDefn featureDefn = layer.GetLayerDefn();
        Map<String, String> fieldMap = new LinkedHashMap<>();
        for (int i = 0; i < featureDefn.GetFieldCount(); i++) {
            FieldDefn fieldDefn = featureDefn.GetFieldDefn(i);
            // 得到属性字段类型
            int fieldType = fieldDefn.GetFieldType();
            String fieldTypeName = fieldDefn.GetFieldTypeName(fieldType);
            // 得到属性字段名称
            String fieldName = fieldDefn.GetName();
            fieldMap.put(fieldName, fieldTypeName);
        }
        return fieldMap;
    }
    /**
     * 根据图层获取当前所有数据
     * @param layer 图层对象
     * @return 数据集合
     */
    public static Map<Feature,Map<String,String>> getData(Layer layer){
        LinkedHashMap<Feature, Map<String,String>> result = new LinkedHashMap<>();
        Feature feature = null;
        Map<String, String> listField = listField(layer);
        while ((feature = layer.GetNextFeature()) != null) {
            Map<String, String> map = new LinkedHashMap<>();
            for (String s : listField.keySet()) {
                map.put(s, feature.GetFieldAsString(s));
            }
            result.put(feature,map);
        }
        return result;
    }


}
